"""
The MIT License

Copyright (c) 2009 AppHacker apphacker@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from __future__ import with_statement
from __future__ import division
import urllib2
import urllib 
from random import getrandbits
from time import time
from time import sleep
import logging
import simplejson
import hmac
import hashlib
import base64
import secret
import kbCookies

REQUEST_URL = "http://twitter.com"
FORMAT = ".json"
REQUEST_TYPE = "POST"

def oauthEncode(binStr):
  return urllib.quote(binStr.encode('utf-8'),'')

def appStr(old, new):
  return "%s<br/>%s" % (old, new)

def makeURL(method, format=FORMAT):
  return "%s%s%s" % (REQUEST_URL, method, format)

def makeValues(token):
  key = secret.key()
  values = [
    ('oauth_consumer_key', key),
    ('oauth_signature_method', 'HMAC-SHA1'),
    ('oauth_timestamp', str(int(time()))),
    ('oauth_nonce', str(getrandbits(64))),
    ('oauth_token', token),
    ('oauth_version', '1.0'),
  ]
  return values

def appendValue(values, key, value):
  return values.append((str(key),str(value)))

def urlEncodeValues(values):
  return [(urllib.quote(k,''),urllib.quote(v,'')) for k,v in values]

def makeSig(values, method, tokenSecret, format=FORMAT, request_type=REQUEST_TYPE):
  secret_ = secret.secret()
  _values = urlEncodeValues(values)
  _values.sort()
  sig_ = "%s&%s&%s" % (request_type, oauthEncode("%s%s%s" % (REQUEST_URL,method, format)), oauthEncode("&".join(("=".join(v) for v in _values))))
  #print "\nsig_ %s\n:" % sig_
  hashKey = "&".join((secret_,tokenSecret))
  hash = hmac.new(hashKey, sig_, hashlib.sha1)
  params = dict(values)
  params['oauth_signature'] = base64.b64encode(hash.digest())
  return params

def makeReq(url, params, request_type=REQUEST_TYPE):
  _params = {}
  for k,v in params.iteritems():
    _params[k.encode('utf-8')] = v.encode('utf-8')
  params = _params
  data = urllib.urlencode(params)
  if request_type == REQUEST_TYPE:
    req = urllib2.Request(url, data)
  else:
    req = urllib2.Request("%s?%s" % (url, data))
  #proxy_handler = urllib2.ProxyHandler({'http':'127.0.0.1:8888'})
  #opener = urllib2.build_opener(proxy_handler)
  #urllib2.install_opener(opener)
  resp = urllib2.urlopen(req)
  return resp.read()

def kbLog(msg):
  logging.info("%s %s %s" % ("\n\nLOGGING:", msg, "\n"))

def reqAuth(handler):
  cookies = kbCookies.Cookies(handler,max_age=1209600)
  if "kb_rt" in cookies:
    token = cookies["kb_rt"]
    tokenSecret = cookies["kb_rs"]
    values = makeValues(token)
    method = "/oauth/access_token"
    url = makeURL(method, '')
    request_type = "GET"
    params = makeSig(values, method, tokenSecret, '', request_type=request_type)
    try: 
      resp = makeReq(url, params, request_type)
      kbLog("getting auth token")
      info = dict(map(lambda x: x.split("="),resp.split("&")))
      cookies["kb_t"] = info["oauth_token"]
      cookies["kb_s"] = info["oauth_token_secret"]
      if "kb_rt" in cookies:
        del cookies["kb_rt"]
      if "kb_rs" in cookies:
        del cookies["kb_rs"]
      handler.redirect("/run") 
      return None
    except urllib2.HTTPError:
      kbLog("Failed auth token request. %s")
  method = "/oauth/request_token"
  token = ''
  tokenSecret = ''
  url = makeURL(method, "")
  values = makeValues(token)
  params = makeSig(values, method, tokenSecret, '')
  resp = makeReq(url, params)
  info = dict(map(lambda x: x.split("="),resp.split("&")))
  cookies["kb_rt"] = info["oauth_token"]
  cookies["kb_rs"] = info["oauth_token_secret"]
  return info["oauth_token"] 

def runApp(handler, token=None, tokenSecret=None):
  cookies = kbCookies.Cookies(handler,max_age=1209600)
  if token:
    cookies = {
      "kb_t":token,
      "kb_s":tokenSecret,
    }
  run = False
  if "kb_t" in cookies:
    token = cookies["kb_t"]
    tokenSecret = cookies["kb_s"]
    values = makeValues(token)
    method = "/account/verify_credentials"
    url = makeURL(method)
    request_type = "GET"
    params = makeSig(values, method, tokenSecret, request_type=request_type)
    try: 
      resp = simplejson.loads(makeReq(url, params, request_type))
      run = True
      cookies["screenName"] = resp["screen_name"]
      kbLog("Authorized")
    except urllib2.HTTPError:
      if "kb_t" in cookies:
        del cookies["kb_t"]
      if "kb_s" in cookies:
        del cookies["kb_s"]
  if not run:
    kbLog("Failed authorization.")
    handler.redirect("/req") 
    return None
  else:
    kbLog("authorized with key: %s and secret %s" % (token, tokenSecret))
    return resp

def getFollowers(handler, user, token=None, tokenSecret=None):
  if not token:
    cookies = kbCookies.Cookies(handler,max_age=1209600)
    token = cookies["kb_t"]
  if not tokenSecret:
    tokenSecret = cookies["kb_s"]
  values = makeValues(token)
  method = "/statuses/followers" 
  url = makeURL(method)
  appendValue(values,"screen_name",user["screen_name"])
  request_type = "GET"
  params = makeSig(values, method, tokenSecret, request_type=request_type)
  try: 
    resp = simplejson.loads(makeReq(url, params, request_type))
  except urllib2.HTTPError, e:
    kbLog("Error getting followers for %s: %s %s" % (user["screen_name"], e.code,e.read()))
    kbLog("failed with key: %s and secret %s" % (token, tokenSecret))
    return "Error"
  return resp

def getSpammerRules():
  return {
      "friendLimit": 5000,
      "minFriends": 100,
      "friendRatio": 1.5,
  }

def getSpammers(followers):
  spammers = []
  rules =  getSpammerRules()
  exceptions = ["spam","wordpress"]
  for follower in followers:
    if follower["followers_count"] > 0:
      friendRatio = follower["friends_count"]/follower["followers_count"]
    else:
      friendRatio = follower["friends_count"]
    spamScore = 0
    if follower["screen_name"] in exceptions:
      #special exception
      continue
    if follower["friends_count"] <= rules["minFriends"]:
      continue
    if follower["friends_count"] > rules["friendLimit"]:
      spammers.append(follower)
      spamScore += 1
    elif friendRatio > rules["friendRatio"]:
      spammers.append(follower)
      spamScore += friendRatio
    follower["spamScore"] = spamScore
    follower["friendRatio"] = friendRatio
  return sorted(spammers, key=lambda x: x["spamScore"], reverse=True) 

def sendNotification(handler, spammerCount, token=None, tokenSecret=None):
  if not token:
    cookies = kbCookies.Cookies(handler,max_age=1209600)
    token = cookies["kb_t"]
  if not tokenSecret:
    tokenSecret = cookies["kb_s"]
  request_type = "POST"
  method = "/statuses/update"
  values = makeValues(token)
  appendValue(values,"status","Blocked %d Twitter spammers with #killbills @ http://gtfokthxbi.appspot.com/" % spammerCount)
  params = makeSig(values, method, tokenSecret, request_type=request_type)
  url = makeURL(method)
  try: 
    resp = simplejson.loads(makeReq(url, params, request_type))
  except urllib2.HTTPError, e:
    kbLog("Couldn't send status update: %s %s" % (e.code,e.read()))
    kbLog("failed with key: %s and secret %s" % (token, tokenSecret))

def blockSpammers(handler, spammers, token=None, tokenSecret=None):
  isFollowingSpam = True
  if not token:
    cookies = kbCookies.Cookies(handler,max_age=1209600)
    token = cookies["kb_t"]
  if not tokenSecret:
    tokenSecret = cookies["kb_s"]
  for spammer in spammers:
    request_type = "POST"
    values = makeValues(token)
    method = "/blocks/create/%s"  % spammer["screen_name"]
    params = makeSig(values, method, tokenSecret, request_type=request_type)
    url = makeURL(method)
    try: 
      resp = simplejson.loads(makeReq(url, params, request_type))
    except urllib2.HTTPError, e:
      kbLog("Couldn't block spammers for %s: %s %s" % (spammer["screen_name"], e.code,e.read()))
      kbLog("failed with key: %s and secret %s" % (token, tokenSecret))
      return
    if isFollowingSpam:
      request_type = "POST"
      values = makeValues(token)
      method = "/direct_messages/new"
      appendValue(values,"user","spam")
      appendValue(values,"text","@%s" % spammer["screen_name"])
      params = makeSig(values, method, tokenSecret, request_type=request_type)
      try:
        resp = simplejson.loads(makeReq(url, params, request_type))
      except urllib2.HTTPError, e:
        isFollowingSpam = False

def logOut(handler):
  cookies = kbCookies.Cookies(handler,max_age=1209600)
  vars = ("screenName", "kb_t", "kb_s", "kb_rt", "kb_rs")
  for var in vars:
    if var in cookies:
      del cookies[var]

def getScreenName(handler):
  cookies = kbCookies.Cookies(handler,max_age=1209600)
  if "screenName" in cookies:
    return cookies["screenName"]
  else:
    return None


def getSpammerRules():
  return {
      "friendLimit": 5000,
      "minFriends": 100,
      "friendRatio": 1.5,
  }



